<?php

require_once __DIR__ . '/vendor/autoload.php';

use Swoole\Http\Request;
use Swoole\Http\Response;

require_once __DIR__ . "/app/config/define.php"; //自定义配置
\Core\BeanFactory::init();//初始化Bean工厂

$dispatcher = \Core\BeanFactory::getBean('RouterCollect')->getDispatcher();


$http = new Swoole\Http\Server("0.0.0.0", 8081);
$http->on('request', function (Request $request, Response $response) use ($dispatcher) {
    $myRequest = \Core\http\Request::init($request);
    $myresponse = \Core\http\Response::init($response);
    $routeInfo = $dispatcher->dispatch($myRequest->getMethod(), $myRequest->getUri());
    switch ($routeInfo[0]) {
        case FastRoute\Dispatcher::NOT_FOUND:
            $response->status(404);
            $response->end();
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $response->status(405);
            $response->end();
            break;
        case FastRoute\Dispatcher::FOUND:
            //访问正确后，调用匿名函数.
            $handler = $routeInfo[1];
            //url地址中的参数
            $vars = $routeInfo[2];
            $ext_params = array(
                $myRequest,
                $myresponse
            );
            $myresponse->setBody($handler($vars,$ext_params));  //相应的body部分
            $myresponse->end();    //如果有参数，将参数传递给最终的执行方法中


            break;
    }
});
$http->start();
